#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

# Copyright (c) 2005-2014 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import os
import sys
import strict_pgs


def usage():
    print('Usage:')
    print('   strict_pgs show [root-directory]')
    print('   strict_pgs verify [root-directory] [--auto-fix]')
    print('')


def die(msg):
    print(msg, file=sys.stderr)
    sys.exit(1)


def doShow():
    if len(sys.argv) >= 3:
        if not sys.argv[2].startswith("/"):
            die("Parameter root-directory must be absolute directory!")
        dirPrefix = sys.argv[2]
    else:
        dirPrefix = "/"

    with strict_pgs.PasswdGroupShadow(dirPrefix=dirPrefix) as pgs:
        print("Normal Users:")
        print("       %s" % (", ".join(pgs.getNormalUserList())))
        print("")
        print("System Users:")
        print("       %s" % (", ".join(pgs.getSystemUserList())))
        print("")
        print("System Groups:")
        print("       %s" % (", ".join(pgs.getSystemGroupList())))
        print("")
        print("Redundant Users:")
        print("       %s" % (", ".join(pgs.getRedundantUserList())))
        print("")
        print("Redundant Groups:")
        print("       %s" % (", ".join(pgs.getRedundantGroupList())))
        print("")


def doVerify():
    if len(sys.argv) >= 3:
        if sys.argv[2] == "--auto-fix":
            autoFix = True
        else:
            if not sys.argv[2].startswith("/"):
                die("Parameter root-directory must be absolute directory!")
            dirPrefix = sys.argv[2]
    else:
        dirPrefix = "/"

    if len(sys.argv) >= 4:
        if sys.argv[3] != "--auto-fix":
            die("Only --auto-fix is allowed as parameter!")
        autoFix = True
    else:
        autoFix = False

    if autoFix:
        with strict_pgs.PasswdGroupShadow(dirPrefix=dirPrefix, readOnly=False) as pgs:
            pass

    with strict_pgs.PasswdGroupShadow(dirPrefix=dirPrefix) as pgs:
        pg.verify()


if __name__ == '__main__':
    if len(sys.argv) <= 1:
        usage()
        sys.exit(1)

    if sys.argv[1] == "--help":
        usage()
        sys.exit(0)

    if os.getuid() != 0:
        die("You must run this command as root!")

    op = sys.argv[1]
    if op == "show":
        doShow()
    elif op == "fix":
        doVerify()
    else:
        die('Invalid operation.')
